package sk.mka.utils.tools.filesystem;

import java.io.File;
import org.apache.log4j.Logger;

/**
 *
 * @author katrami
 * @date Aug 26, 2010
 */
public class DirectoryUtils {

    private final static Logger log = Logger.getLogger(DirectoryUtils.class);

    public static final boolean removeDirectory(File directory) {


        // System.out.println("removeDirectory " + directory);

        if (directory == null) {
            return false;
        }
        if (!directory.exists()) {
            return true;
        }
        if (!directory.isDirectory()) {
            return false;
        }

        String[] list = directory.list();

        // Some JVMs return null for File.list() when the
        // directory is empty.
        if (list != null) {
            for (int i = 0; i < list.length; i++) {
                File entry = new File(directory, list[i]);

                //        System.out.println("\tremoving entry " + entry);

                if (entry.isDirectory()) {
                    if (!removeDirectory(entry)) {
                        return false;
                    }
                } else {
                    if (!entry.delete()) {
                        return false;
                    }
                }
            }
        }

        return directory.delete();
    }

    public static final void createDirectory(final String filename) {
        // Create a directory; all ancestor directories must exist
//        boolean success = (new File(filename)).mkdir();
//        if (!success) {
//            // Directory creation failed
//            log.fatal("!!! Directory creation failed: " + filename);
//
//        }

// Create a directory; all non-existent ancestor directories are
// automatically created
        boolean success = (new File(filename)).mkdirs();
        if (!success) {
            // Directory creation failed
            log.fatal("!!! Directory creation failed: " + filename);
        }
    }
}
